#include"recvF.h"
#include"proto.h"
#include<errno.h>
#include<arpa/inet.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/socket.h>
#include"sysif.h"
#include<unistd.h>
#define THREAD_NUM 3

int main(int argc, char* argv[])
{
	int sock = socket(PF_INET, SOCK_STREAM,0);
	struct sockaddr_in addr;
	char *srcFileName, *destFileName, *serverIP;
	if (argc != 4&&argc !=3)
	{
		printf(" Usage: ./main servIP srcfilename [destfilename] ");
		return -1;
	}
	
	serverIP = argv[1];
	srcFileName = argv[2];
	if (argc == 3)
		destFileName = argv[2];
	else
		destFileName = argv[3];

	addr.sin_family=AF_INET;
	addr.sin_port = PORT;
	addr.sin_addr.s_addr = inet_addr(serverIP);
	if (connect(sock,(struct sockaddr*)&addr, sizeof(addr)))
	{
		printf("Fatal error : Connection Fault\n");
		perror("Msg:");
		return -1;
	}
	
	printf("%d\n", strlen(srcFileName));
	int i;
	pthread_t tid[THREAD_NUM];
	int len = getFileLen(sock, srcFileName, strlen(srcFileName));
	if (len < 0)
	{
		printf("Fatal error : Illegel source file\n");
		return -1;
	}
	printf("All set for transferring %s(%dByte) from %s, Moving>>>\n", srcFileName, len, serverIP);

	int slen = len / THREAD_NUM;//Segment length
	for (i=0; i<THREAD_NUM; i++)
	{
		pThreadArg targ=malloc(sizeof(threadArg));

		int start = i*slen;
		if (i==THREAD_NUM -1)
			slen = len - start;

		prepareTransfer(srcFileName, strlen(srcFileName), start, slen, &(targ->cmd));
		targ->sock = socket(PF_INET, SOCK_STREAM,0);
		if (connect(targ->sock,(struct sockaddr*)&addr, sizeof(addr)))
		{
			printf("Thread %d fail to create connection to server.", i);
			perror("Msg:");
			continue;
		}
		tid[i] = crtDownThread(targ);
	}
	for(i = 0;i < THREAD_NUM; i++)
		pthread_join(tid[i], NULL);
	return 0;
}
